package cn.bigcontainer.common.util;

import java.io.BufferedOutputStream;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.bigcontainer.common.exception.BCException;

public class BCUtil {

	private static Logger LOG = LoggerFactory.getLogger(BCUtil.class);
	
	/**
	 * @param s
	 * @param val
	 * @return
	 */
	public static Integer parseInt (String s, Integer val) {
		try {
			return Integer.parseInt(s);
		} catch (NumberFormatException e) {
			return val;
		}
	}
	
	/**
	 * @param file
	 * @param wcb
	 */
	public static void writeToFile (String file, WriteCallback wcb) {
		BufferedWriter bw = null; 
		try {
			FileOutputStream fos = new FileOutputStream(file);
			bw = new BufferedWriter (new OutputStreamWriter (new BufferedOutputStream(fos), "utf-8"));
			wcb.write(bw);
		} catch (Exception e) {
			LOG.error("写入文件出错", e);
			throw new BCException (BCConstant.ERR_FILE_WRITE, e);
		} finally {
			try {
				bw.close();
			} catch (Exception e) {
			}
		}
	}
	
	public static interface WriteCallback {
		void write (Writer writer) throws Exception;
	}
	
	public static void mkdirs (String path) {
		File dir = new File (path);
		if (dir.isDirectory()) {
			dir.mkdirs();
		} else {
			dir.getParentFile().mkdirs();
		}
	}
}
